package ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dispatchapp.andlei.R;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import base.BaseBean;
import base.fragment.BaseFragment;
import bean.RiderInfoBean;
import netWork.NetUtils;
import ui.activity.login.LoginActivity;
import ui.activity.mine.DeliveryAreaActivity;
import ui.activity.mine.IdentityActivity;
import ui.activity.mine.MyAssessActivity;
import ui.activity.mine.MyWalletActivity;
import ui.activity.mine.NotificationSettingActivity;
import ui.activity.mine.WorkingRiderActivity;
import utils.APKVersionCodeUtils;
import utils.GlideUtils;
import utils.GsonUtils;
import utils.SPUtils;
import widget.CircleImageView;
import widget.HiDialog;
import widget.ShopStatusPopupWindow;
import widget.SwitchIdentityyPopupWindow;

/**
 * 我的頁面
 *
 * @author Andlei
 */
public class MineFragment extends BaseFragment {
    private CircleImageView circleImageView;
    private TextView tv_name;
    private ImageView img_unauthorized,img_state,img_identity;
    private TextView tv_finish_order,tv_income_order;
    private LinearLayout layout_assess,layout_area,layout_position,layout_wallet,layout_identity,layout_phone,layout_rider,layout_notification;
    private TextView tv_identy,tv_phone;
    private Button btn_loginout;
    private TextView tv_version;
    private ShopStatusPopupWindow pop;
    private SwitchIdentityyPopupWindow spop;
    private View mView;
    private boolean isInorder;//判断是否营业
    private String is_card ="";
    private NetUtils netUtils;
    public static boolean ischangeIdentity = false;
    public static MineFragment getInstance() {
        return new MineFragment();
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        //设置title文本
        this.mView = view;
        setTitle("我的");
        hideBack();
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
           // toast("隐藏了");
        } else {
            netUtils.post("rider/user/rider-info",BaseBean.class,false);
           // toast("显示了");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void findViews() {
        netUtils = new NetUtils(mActivity,netRequestCallBack);
        circleImageView = getView(R.id.img_mine_photo);
        tv_name = getView(R.id.tv_name);
        tv_finish_order = getView(R.id.tv_finish_order);
        tv_income_order = getView(R.id.tv_income_order);
        tv_identy = getView(R.id.tv_identy);
        tv_phone = getView(R.id.tv_phone);
        img_unauthorized = getView(R.id.img_unauthorized);
        img_state = getView(R.id.img_state);
        img_identity = getView(R.id.img_identity);

        layout_assess = getView(R.id.layout_myassess);
        layout_area = getView(R.id.layout_area);
        layout_identity = getView(R.id.layout_identity);
        layout_position = getView(R.id.layout_position);
        layout_wallet = getView(R.id.layout_wallet);
        layout_phone = getView(R.id.layout_phone);
        layout_rider = getView(R.id.layout_rider);
        layout_notification = getView(R.id.layout_notification_setting);
        btn_loginout = getView(R.id.btn_loginout);
        tv_version = getView(R.id.tv_version);
        tv_version.setText("版本V:"+ APKVersionCodeUtils.getVerName(mActivity));
    }

    @Override
    protected void formatViews() {
        circleImageView.setOnClickListener(this);
        img_state.setOnClickListener(this);

        layout_assess.setOnClickListener(this);
        layout_area.setOnClickListener(this);
        layout_phone.setOnClickListener(this);
        layout_wallet.setOnClickListener(this);
        layout_position.setOnClickListener(this);
        layout_identity.setOnClickListener(this);
        layout_rider.setOnClickListener(this);
        layout_notification.setOnClickListener(this);
        btn_loginout.setOnClickListener(this);
    }
    @Override
    protected void formatData() {
        netUtils.post("rider/user/rider-info",BaseBean.class,false);
    }
    @Override
    protected void getBundle(Bundle bundle) {

    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()){
            case R.id.img_mine_photo:
                //点击头像
                if(tv_name.getText().toString().equals("未登录")){

                }

                break;
            case R.id.img_state:
                //状态
                if(pop == null){
                    pop = new ShopStatusPopupWindow(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Map<String,Object> map = new HashMap<>();
                            if(view.getId() == R.id.tv_open){
                                map.put("states","1");
                               // img_state.setImageResource(R.mipmap.icon_inorder);
                            }else {
                                map.put("states","2");
                               // img_state.setImageResource(R.mipmap.icon_inrest);
                            }
                            pop.dismiss();
                            netUtils.post("rider/user/change-states",map,BaseBean.class,false);
                        }
                    }, false);
                    pop.showAtLocation(mView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,0);
                }else {
                    pop.showAtLocation(mView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,0);
                }
                break;
            case R.id.layout_myassess:
                //跳转至我的评价
                jumpTo(MyAssessActivity.class);
                break;
            case R.id.layout_area:
                if(SPUtils.getInstance(mActivity).getString("Is_coach").equals("2")){
                    toast("调度员切换配送区域请联系客服");
                    return;
                }
                //跳转至区域界面
                jumpTo(DeliveryAreaActivity.class);
                break;
            case R.id.layout_position:
                //切换职位
                if(SPUtils.getInstance(mActivity).getString("Is_coach").equals("2")){
                    toast("调度员切换身份请联系客服");
                }else if(SPUtils.getInstance(mActivity).getString("Is_coach").equals("1")||SPUtils.getInstance(mActivity).getString("Is_coach").equals("3")){
                    if(spop == null){
                        spop = new SwitchIdentityyPopupWindow(getActivity(), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                spop.dismiss();
                                Map<String,Object> map = new HashMap<>();
                                if(spop.ReturnCheck()==1){
                                    map.put("change","school");
                                }else if(spop.ReturnCheck() ==3){
                                    map.put("change","out_school");
                                }else {
                                    return;
                                }
                                netUtils.get("rider/user/change-identity",map,BaseBean.class,null,false);
                            }
                        }, SPUtils.getInstance(mActivity).getString("Is_coach"));
                        spop.showAtLocation(mView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL,0,0);
                    }else {
                        spop.showAtLocation(mView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL,0,0);
                    }
                }
                break;
            case R.id.layout_notification_setting:
                //跳转至 通知设置界面
                jumpTo(NotificationSettingActivity.class);
                break;
            case R.id.layout_rider:
                //调度员查看上班骑手
                jumpTo(WorkingRiderActivity.class);
                break;
            case R.id.layout_identity:
                //跳转至身份认证界面
                if (tv_identy.getText().equals("审核通过")){
                    toast("审核已通过");
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("is_card",is_card);
                jumpTo(IdentityActivity.class,bundle);
                break;
            case R.id.layout_phone:
                //拨打手机号
                callPhone(tv_phone.getText().toString());
                break;
            case R.id.layout_wallet:
                //跳转至钱包界面
                jumpTo(MyWalletActivity.class);
                break;
            case R.id.btn_loginout:
                new HiDialog.Builder(getActivity())
                        .setContent("退出登录后将收不到新订单，确定要退出登录吗？")
                        .setLeftBtnText("取消")
                        .setRightBtnText("确定")
                        .setRightCallBack(new HiDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                //退出登录
                                netUtils.get("rider/user/logout",BaseBean.class,true);
                            }
                        }).build();
                break;
        }
    }

    private NetUtils.NetRequestCallBack netRequestCallBack = new NetUtils.NetRequestCallBack() {
        @Override
        public void success(String action, BaseBean t, Map tag) {
            switch (action){
                case "rider/user/rider-info":
                    if(t.getCode() == 200){
                        RiderInfoBean bean = (RiderInfoBean) GsonUtils.getInstance(mContext).parseComplexJArrayByCommon(t,RiderInfoBean.class);
                        initData(bean);
                    }else {
                        toast(t.getMsg());
                    }
                    break;
                case "rider/user/logout":
                    if(t.getCode() == 200){
                        toast("退出登录成功");
                    }else {
                        toast(t.getMsg());
                    }
                    jumpTo(LoginActivity.class);
                    SPUtils.getInstance(mActivity).put("token","");
                    mActivity.finish();
                    break;
                case "rider/user/change-states":
                    if(t.getCode() != 200){
                        toast(t.getMsg());
                    }else {
                        netUtils.post("rider/user/rider-info",BaseBean.class,false);
                    }
                    break;
                case "rider/user/change-identity":
                    if(t.getCode() != 200){
                        toast(t.getMsg());
                    }else {
                        ischangeIdentity = true;
                        netUtils.post("rider/user/rider-info",BaseBean.class,false);
                    }
                    break;
            }
        }
        @Override
        public void error(String action, Throwable e, Map tag) {
            if(action.equals("rider/user/logout")){
                jumpTo(LoginActivity.class);
                SPUtils.getInstance(mActivity).put("token","");
                mActivity.finish();
            }
        }
    };
    private void initData(RiderInfoBean bean){
        tv_name.setText(bean.getNickname());
        tv_phone.setText(bean.getServer_tel());
        GlideUtils.loadImageView(mContext,bean.getFace(),circleImageView);
        tv_finish_order.setText(bean.getOrder_num());
        try {
            tv_income_order.setText(MyWalletActivity.changeF2Y(bean.getMoney()));
        } catch (Exception e) {
            e.printStackTrace();
            toast("金额格式有误");

        }
        //是否审核通过，0未认证，1审核中，2审核通过，3未通过
        is_card = bean.getIs_card();
        if(bean.getIs_card().equals("3")){
            tv_identy.setText("审核未通过");
            img_unauthorized.setImageResource(R.mipmap.icon_unauthorized);
            img_unauthorized.setVisibility(View.VISIBLE);
            img_state.setVisibility(View.GONE);
            img_identity.setVisibility(View.GONE);
        }else if(bean.getIs_card().equals("2")){
            tv_identy.setText("审核通过");
            img_unauthorized.setVisibility(View.GONE);
            img_state.setVisibility(View.VISIBLE);
            img_identity.setVisibility(View.VISIBLE);
        }else if(bean.getIs_card().equals("1")){
            tv_identy.setText("审核中");
            img_unauthorized.setImageResource(R.mipmap.icon_inreview);
            img_unauthorized.setVisibility(View.VISIBLE);
            img_state.setVisibility(View.GONE);
            img_identity.setVisibility(View.GONE);
        }else {
            tv_identy.setText("未认证");
            img_unauthorized.setImageResource(R.mipmap.icon_unauthorized);
            img_unauthorized.setVisibility(View.VISIBLE);
            img_state.setVisibility(View.GONE);
            img_identity.setVisibility(View.GONE);
        }
        //0不可切换身份  1可切换身份
//        if(bean.getIs_identity().equals("0")){
//            layout_position.setEnabled(false);
//            layout_position.setBackgroundResource(R.color.gray);
//        }else {
//            layout_position.setEnabled(true);
//            layout_position.setBackgroundResource(R.color.white);
//        }
        //1接单中  2休息
        if(bean.getStates().equals("1")){
            isInorder = true;
            img_state.setImageResource(R.mipmap.icon_inorder);
        }else {
            isInorder = false;
            img_state.setImageResource(R.mipmap.icon_inrest);
        }
        //1校内骑手  2调度员 3校外骑手 0未指定身份
        SPUtils.getInstance(mActivity).put("Is_coach",bean.getIs_coach());
        SPUtils.getInstance(mActivity).put("open_id",bean.getOpen_id());
        if(bean.getIs_coach().equals("1")){
            img_identity.setImageResource(R.mipmap.icon_song_can);
            layout_rider.setVisibility(View.GONE);
            layout_assess.setVisibility(View.VISIBLE);
        }else if(bean.getIs_coach().equals("2")){
            img_identity.setImageResource(R.mipmap.icon_dispatcher);
            layout_rider.setVisibility(View.VISIBLE);
            layout_assess.setVisibility(View.GONE);
        }else if(bean.getIs_coach().equals("3")){
            layout_assess.setVisibility(View.VISIBLE);
            layout_rider.setVisibility(View.GONE);
            img_identity.setImageResource(R.mipmap.icon_qu_can);
        }else {
            img_state.setVisibility(View.GONE);
            img_identity.setImageResource(android.R.color.white);
        }
    }
    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNumber 电话号码
     */
    @SuppressLint("MissingPermission")
    public void  callPhone(final String phoneNumber) {
        if (mActivity == null || android.text.TextUtils.isEmpty(phoneNumber)) {
            return;
        }
        //6.0权限处理
        Acp.getInstance(mActivity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.CALL_PHONE).build(), new AcpListener() {
            @SuppressLint("MissingPermission")
            @Override public void onGranted() {
                Uri u = Uri.parse("tel:" + phoneNumber);
                Intent it = new Intent(Intent.ACTION_CALL, u);
                mActivity.startActivity(it);
            }
            @Override public void onDenied(List<String> permissions) {
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
